package com.centaline.androidsalesblog.fragments.list;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import com.android.volley.VolleyError;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.sale.EsfSaleListActivity;
import com.centaline.androidsalesblog.adapter.EsfNewsAdapter;
import com.centaline.androidsalesblog.api.sale.EsfEstateListApi;
import com.centaline.androidsalesblog.api.usercenter.CollectInfoChangeApi;
import com.centaline.androidsalesblog.api.usercenter.UpdateCollectIsRead;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.base.BaseFragment;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.iml.RecyclerViewItemOnClickListener;
import com.centaline.androidsalesblog.model.businissobject.CollectInfoChangeBo;
import com.centaline.androidsalesblog.model.databaseobject.EsfEstateDo;
import com.centaline.androidsalesblog.model.responseobject.CollectInfoChangeRo;
import com.centaline.androidsalesblog.model.responseobject.EsfEstateListRo;
import com.centaline.androidsalesblog.model.responseobject.SimpleUserCenterRo;
import com.centaline.androidsalesblog.widgets.MRecyclerView;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.interfaces.IRecycleViewListener;
import com.centanet.framework.interfaces.IResponseListener;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * 小区动态
 * Created by guilin on 16/3/30.
 */
public class EsfNewsFragment extends BaseFragment {

    private MRecyclerView mRecyclerView;
    private boolean isRequest;

    private ArrayList<CollectInfoChangeBo> collectInfoChangeBos = new ArrayList<>();
    private ArrayList<CollectInfoChangeBo> collectInfoChangeBos2 = new ArrayList<>();
    private ArrayList<String> estateIds = new ArrayList<>();
    private ArrayList<EsfEstateDo> temp;
    private CollectInfoChangeApi collectInfoChangeApi;
    private EsfEstateListApi esfEstateListApi;
    private int pageNumber = 0; //分页页码
    private boolean isRepeat = false;
    private UpdateCollectIsRead updateCollectIsRead;
    private CollectInfoChangeBo collectInfoChangeBo;
    private int positionClick;


    @Override
    protected int setLayoutId() {
        return R.layout.layout_m_recyclerview;
    }

    @Override
    protected void findViews(View view) {
        mRecyclerView = (MRecyclerView) view.findViewById(R.id.mRecyclerView);
    }

    @Override
    protected void initView() {
        mRecyclerView.setIRecycleViewListener(new IRecycleViewListener() {

            @Override
            public void downRefresh() {
                collectInfoChangeApi.startRequest();
            }

            @Override
            public void upRefresh() {
                if (temp.size() == 10) {
                    pageNumber = collectInfoChangeBos2.size() / 10;
                    requestEstateList();
                } else {
                    mRecyclerView.stopRefresh(false);
                }
            }

            @Override
            public void onItemClick(int position) {
                EsfEstateDo esfEstateDo = collectInfoChangeBos2.get(position).getEsfEstateDo();
                collectInfoChangeBo = collectInfoChangeBos2.get(position);
                positionClick = position;
                markIsRead();
                if (esfEstateDo != null) {
                    startActivity(new Intent(getActivity(), EsfSaleListActivity.class)
                            .putExtra(ExtraConstant.CestCode, esfEstateDo.getCestCode())
                            .putExtra(ExtraConstant.BeginTime, ((System.currentTimeMillis() - 1000 * 3600 * 24)/1000) + "")
                            .putExtra(ExtraConstant.EndTime,(System.currentTimeMillis()/1000)+"")
                            .putExtra(BaseActivity.TITLE_ACTIVITY,esfEstateDo.getName()));
                }
            }
        });
        mRecyclerView.setAdapter(new EsfNewsAdapter(getActivity(), GlideLoad.init(this), collectInfoChangeBos, new RecyclerViewItemOnClickListener<CollectInfoChangeBo>() {
            @Override
            public void onItemOnClick(CollectInfoChangeBo collectInfoChangeBo, int tag) {

            }
        }));
        collectInfoChangeApi = new CollectInfoChangeApi(EsfNewsFragment.class, CollectInfoChangeRo.class, new IResponseListener<CollectInfoChangeRo>() {
            @Override
            public void onResponse(CollectInfoChangeRo collectInfoChangeRo) {
                ArrayList<CollectInfoChangeBo> temp = collectInfoChangeRo.getCollectInfoChangeBos();
                pageNumber = 0;
                collectInfoChangeBos.clear();
                collectInfoChangeBos2.clear();
                estateIds.clear();
                isRepeat = false;
                if (temp == null || temp.size() == 0) {
                    mRecyclerView.stopRefresh(false);
                    snack(collectInfoChangeRo.getMessage());
                } else {
                    for (CollectInfoChangeBo collectInfoChangeBo : temp) {
                        if ("estcount".equalsIgnoreCase(collectInfoChangeBo.getChangeType())) {
                            if (estateIds.size() > 0) {
                                for (String estateId : estateIds) {
                                    if (collectInfoChangeBo.getCollectInfoBo().getCollectValue().equals(estateId))
                                        isRepeat = true;
                                }
                                if (!isRepeat) {
                                    collectInfoChangeBos.add(collectInfoChangeBo);
                                    estateIds.add(collectInfoChangeBo.getCollectInfoBo().getCollectValue().toLowerCase());
                                } else {
                                    isRepeat = false;
                                }
                            } else {
                                collectInfoChangeBos.add(collectInfoChangeBo);
                                estateIds.add(collectInfoChangeBo.getCollectInfoBo().getCollectValue().toLowerCase());
                            }
                        }
                    }
                    requestEstateList();
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                mRecyclerView.refreshError();
            }
        });
        collectInfoChangeApi.setChangeType("estcount");
        esfEstateListApi = new EsfEstateListApi(EsfNewsFragment.class, EsfEstateListRo.class, new IResponseListener<EsfEstateListRo>() {
            @Override
            public void onResponse(EsfEstateListRo esfEstateListRo) {
                temp = esfEstateListRo.getList();
                if (temp == null) {
                    mRecyclerView.stopRefresh(false);
                } else {
                    for (EsfEstateDo esfEstateDo : temp) {
                        collectInfoChangeBos.get(estateIds.indexOf(esfEstateDo.getCestCode().toLowerCase())).setEsfEstateDo(esfEstateDo);
                    }
                    int maxSize = (pageNumber + 1) * 10 > collectInfoChangeBos.size() ? collectInfoChangeBos.size() : (pageNumber + 1) * 10;
                    collectInfoChangeBos2.addAll(collectInfoChangeBos.subList(pageNumber * 10, maxSize));
                    Iterator<CollectInfoChangeBo> colIter = collectInfoChangeBos2.iterator();
                    while (colIter.hasNext()) {
                        CollectInfoChangeBo collectInfoChangeBo = colIter.next();
                        if (collectInfoChangeBo.getEsfEstateDo() == null)
                            colIter.remove();
                    }
                    mRecyclerView.stopRefresh(true);
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                mRecyclerView.refreshError();
            }
        });
        esfEstateListApi.setType("");
        esfEstateListApi.setPosttype("");
    }

    /**
     * 请求小区列表
     */
    private void requestEstateList() {
        StringBuilder ids = new StringBuilder();
        int maxSize = (pageNumber + 1) * 10;
        for (int i = pageNumber * 10; i < estateIds.size() && i < maxSize; i++) {
            ids.append(estateIds.get(i)).append(",");
        }
        if (TextUtils.isEmpty(ids)) {
            mRecyclerView.stopRefresh(false);
        } else {
            if (ids.toString().contains(",")) {
                ids.deleteCharAt(ids.length() - 1);
                esfEstateListApi.setCestcodes(ids.toString());
                esfEstateListApi.startRequest();
            }
        }
    }

    private void markIsRead() {
        if (updateCollectIsRead == null)
            updateCollectIsRead = new UpdateCollectIsRead(PostNewsFragment.class, SimpleUserCenterRo.class, new IResponseListener<SimpleUserCenterRo>() {
                @Override
                public void onResponse(SimpleUserCenterRo simpleUserCenterRo) {
                    collectInfoChangeBo.setRead(true);
                    mRecyclerView.notifyItemChanged(positionClick);
                }

                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });
        updateCollectIsRead.setCollectID(collectInfoChangeBo.getCollectID());
        updateCollectIsRead.startRequest();
    }

    @Override
    protected void loadData() {
        if (!isRequest) {
            isRequest = true;
            mRecyclerView.startRefresh();
        }
    }

}
